package utility;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import java.util.concurrent.ExecutionException;

/**
 * Created by lit on 2018/4/12.
 */
public class Serialize {
    /**
     * 将对象序列化为字符数组
     * @param object
     * @return
     */
    public static byte[] serialize(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        if(object != null){
            try{
                baos = new ByteArrayOutputStream();

                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] byt = baos.toByteArray();
                oos.close();
                baos.close();
                return Base64.getEncoder().encode(byt);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 反序列化
     * @param byt
     * @return
     */
    public static Object unserialize(byte[] byt){
        ObjectInputStream ois = null;
        ByteArrayInputStream bais = null;
        if(byt != null){
            try{
                bais = new ByteArrayInputStream(Base64.getDecoder().decode(byt));
                ois = new ObjectInputStream(bais);
                Object object = ois.readObject();
                ois.close();
                bais.close();
                return object;
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
